package Solution.problem086.PartitionList;

import common.ListNode;
import org.junit.Test;

/**
 * @program Leetcode
 * @description:
 *
 * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
 *
 * You should preserve the original relative order of the nodes in each of the two partitions.
 *
 * Example:
 *
 * Input: head = 1->4->3->2->5->2, x = 3
 * Output: 1->2->2->4->3->5
 *
 * @author: lishangsheng
 * @create: 2019/06/17 17:44
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head==null){
            return null;
        }
        /*初始化开始值*/
        ListNode result=new ListNode(x);
        /*新建指针*/
        ListNode temp1=result;

        ListNode needCheck=new ListNode(x);
        needCheck.next=head;
        ListNode temp2=needCheck;

        while (needCheck.next!=null){
            int val=needCheck.next.val;
            if(val<x){
                result.next=new ListNode(val);
                result=result.next;
                needCheck.next=needCheck.next.next;
            }else {
                needCheck=needCheck.next;
            }
        }
        result.next=temp2.next;
        return temp1.next;
    }

    @Test
    public void test() {
        //1->2->3->4->5
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(16);
        ListNode listNode3 = new ListNode(7);
        ListNode listNode4 = new ListNode(3);
        ListNode listNode5 = new ListNode(4);
        ListNode listNode6 = new ListNode(4);
        ListNode listNode7 = new ListNode(5);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode6;
        listNode6.next = listNode7;
/*        ListNode result = partition(listNode1,1);
        System.out.println(result);*/

        ListNode result2 = partition(listNode1,5);
        System.out.println(result2);

        ListNode result3 = partition(listNode1,4);
        System.out.println(result3);

        ListNode result4 = partition(listNode1,17);
        System.out.println(result4);
    }
}
